package cn.iocoder.yudao.module.mqtt.controller.admin.systemconfig;

import cn.iocoder.yudao.module.mqtt.util.SysInfoUtil;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.mqtt.controller.admin.systemconfig.vo.*;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.systemconfig.SystemConfigDO;
import cn.iocoder.yudao.module.mqtt.service.systemconfig.SystemConfigService;

@Tag(name = "管理后台 - MQTT系统配置")
@RestController
@RequestMapping("/mqtt/system-config")
@Validated
public class SystemConfigController {

    @Resource
    private SystemConfigService systemConfigService;

    @PostMapping("/create")
    @Operation(summary = "创建MQTT系统配置")
    @PreAuthorize("@ss.hasPermission('mqtt:system-config:create')")
    public CommonResult<Long> createSystemConfig(@Valid @RequestBody SystemConfigSaveReqVO createReqVO) {
        return success(systemConfigService.createSystemConfig(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新MQTT系统配置")
    @PreAuthorize("@ss.hasPermission('mqtt:system-config:update')")
    public CommonResult<Boolean> updateSystemConfig(@Valid @RequestBody SystemConfigSaveReqVO updateReqVO) {
        systemConfigService.updateSystemConfig(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除MQTT系统配置")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mqtt:system-config:delete')")
    public CommonResult<Boolean> deleteSystemConfig(@RequestParam("id") Long id) {
        systemConfigService.deleteSystemConfig(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除MQTT系统配置")
                @PreAuthorize("@ss.hasPermission('mqtt:system-config:delete')")
    public CommonResult<Boolean> deleteSystemConfigList(@RequestParam("ids") List<Long> ids) {
        systemConfigService.deleteSystemConfigListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得MQTT系统配置")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mqtt:system-config:query')")
    public CommonResult<SystemConfigRespVO> getSystemConfig(@RequestParam("id") Long id) {
        SystemConfigDO systemConfig = systemConfigService.getSystemConfig(id);
        return success(BeanUtils.toBean(systemConfig, SystemConfigRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得MQTT系统配置分页")
//    @PreAuthorize("@ss.hasPermission('mqtt:system-config:query')")
    public CommonResult<PageResult<SystemConfigRespVO>> getSystemConfigPage(@Valid SystemConfigPageReqVO pageReqVO) {
        PageResult<SystemConfigDO> pageResult = systemConfigService.getSystemConfigPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, SystemConfigRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得MQTT系统配置")
    public CommonResult<List<SystemConfigLoginRespVO>> list(SystemConfigDO ddo) {
        List<SystemConfigDO> list = systemConfigService.selectList(ddo);
        return success(BeanUtils.toBean(list, SystemConfigLoginRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出MQTT系统配置 Excel")
    @PreAuthorize("@ss.hasPermission('mqtt:system-config:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSystemConfigExcel(@Valid SystemConfigPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<SystemConfigDO> list = systemConfigService.getSystemConfigPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "MQTT系统配置.xls", "数据", SystemConfigRespVO.class,
                        BeanUtils.toBean(list, SystemConfigRespVO.class));
    }

    /**
     * 获取cpu使用率、内存使用率、系统盘使用率
     * @return
     */
    @GetMapping("/usage")
    @Operation(summary = "获取系统资源使用率")
    public CommonResult<Map<String, Object>> getSystemUsage() {
        try {
            // 直接调用 SysInfoUtil 的静态方法
            String jsonString = SysInfoUtil.getSysUsageForFrontend();
            // 解析JSON字符串为Map对象
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> data = objectMapper.readValue(jsonString, Map.class);
            return success(data);
        } catch (Exception e) {
            // 如果解析失败，返回空数据
            Map<String, Object> emptyData = new HashMap<>();
            emptyData.put("cpu", Map.of("used", 0, "free", 100));
            emptyData.put("memory", Map.of("used", 0, "free", 100));
            emptyData.put("disk", Map.of("used", 0, "free", 100));
            return success(emptyData);
        }
    }
}